import React, { Component } from "react";
import { Link, Route, Switch, Redirect, withRouter } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>home页面</div>;
  }
}

class About extends Component {
  render() {
    return <div>about页面</div>;
  }
}

class Mine extends Component {
  render() {
    return <div>mine页面</div>;
  }
}

@withRouter
class Login extends Component {
  // constructor(props) {
  //   super(props);
  //   this.state = {
  //     from: props.location.state.from,
  //   };
  // }

  login = () => {
    localStorage.setItem("token", "123");
    // 跳转(编程式导航)
    // history对象下面有很多跳转的方法 push replace go goBack
    const history = this.props.history;
    history.push(this.props.location.state.from);
  };

  render() {
    return (
      <div>
        登录页面 - <button onClick={this.login}>登录</button>
      </div>
    );
  }
}

// Auth组件就是封装的路由鉴权的组件，类似于全局的路由守卫
class Auth extends Component {
  render() {
    return (
      <Route
        path={this.props.path}
        render={() => {
          if (localStorage.getItem("token")) {
            return this.props.children;
          } else {
            return (
              <Redirect
                to={{
                  pathname: "/login",
                  state: {
                    from: this.props.path,
                  },
                }}
              ></Redirect>
            );
          }
        }}
      ></Route>
    );
  }
}

class App extends Component {
  render() {
    return (
      <>
        <h3>react-router-路由鉴权</h3>
        <ul>
          <li>
            <Link to="/home">home</Link>
          </li>
          <li>
            <Link to="/about">about</Link>
          </li>
          <li>
            <Link to="/mine">mine</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route path="/home" component={Home}></Route>
          {/* <Route path="/about" component={About}></Route> */}
          {/* <Route
            path="/mine"
            render={() => {
              if (localStorage.getItem("token")) {
                return <Mine />;
              } else {
                // 没有登录的时候需要重定向到登录页
                return <Redirect to="/login"></Redirect>;
              }
            }}
          ></Route> */}

          <Auth path="/about">
            <About />
          </Auth>

          <Auth path="/mine">
            <Mine />
          </Auth>

          <Route path="/login">
            <Login />
          </Route>
        </Switch>
      </>
    );
  }
}

export default App;
